package com.dongzili.common.init;

import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import jakarta.annotation.PostConstruct;

import javax.sql.DataSource;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;

@Order(2)
@Configuration
public class DBInitConfig {

    @Value("${spring.datasource.dynamic.datasource.main.url}")
    private String dbUrl;
    @Resource
    private DynamicDataSourceProvider dynamicDataSourceProvider;

    @PostConstruct
    public void initSqlite() throws Exception {

        String dbPath = dbUrl.replaceAll("jdbc:sqlite:", "");
        File dbFile = new File(dbPath);

        // 1. 判断文件是否存在
        if (!dbFile.exists()) {
            // 2. 如果不存在，创建目录和空文件
            if (!dbFile.getParentFile().exists()) {
                if(dbFile.getParentFile().mkdirs()){
                    Files.createFile(Paths.get(dbFile.toURI()));
                }else{
                    throw new Exception("创建数据库目录失败: "+dbFile.getParentFile().getAbsolutePath());
                }
            }
        }
        if (dbFile.length() < 16384){
            DataSource mainDataSource = dynamicDataSourceProvider.loadDataSources().get("main");
            // 3. 获取连接并执行 SQL 脚本
            try (Connection connection = mainDataSource.getConnection()) {
                ScriptUtils.executeSqlScript(connection, new ClassPathResource("sqlite.sql"));

            }
        }
        System.out.println("数据库初始化完毕...");
    }
}
